package com.fenghuaxz.rpcframework;

import io.netty.bootstrap.AbstractBootstrap;
import io.netty.bootstrap.Bootstrap;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.GenericFutureListener;

import java.net.InetSocketAddress;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 创建 : 七羽软件工作室
 * 时间 : 2017/9/28 : 6:59
 */
public class BindRunnble implements Runnable, ChannelFutureListener {

    private Object abs = null;
    private InetSocketAddress address = null;
    private ReentrantLock lock = null;
    private Condition signal = null;
    public Exception exp = null;

    public <T extends AbstractBootstrap> BindRunnble(T bootstrap, InetSocketAddress address,ReentrantLock lock,Condition signal) throws Exception{
        if (bootstrap == null || address == null) throw new NullPointerException();
        this.abs = bootstrap;
        this.address = address;
        this.lock = lock;
        this.signal = signal;
    }

    @Override
    public void run() {
        try {
            ChannelFuture future = (abs instanceof ServerBootstrap ? ((ServerBootstrap) abs).bind(address) : ((Bootstrap)abs).connect(address)).sync();
            unlock();
            future.channel().closeFuture().sync();
        }catch (Exception e){
            this.exp = e;
            unlock();
        }
    }

    @Override
    public void operationComplete(ChannelFuture channelFuture) throws Exception {
        if (channelFuture.isSuccess())unlock();
    }

    private final void unlock(){
        lock.lock();
        try {
            signal.signal();
        }finally {
            lock.unlock();
        }
    }
}
